<!-- <script setup lang="ts">
import axios from 'axios'
import styles from './Seach.module.css'
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'

const search = ref('')
const history = ref<string[]>(JSON.parse(localStorage.getItem('searchHistory') || '[]'))

const foundTags = ref([
  { text: '宿舍防尘膜' },
  { text: '鼠标' },
  { text: '防尘膜' },
  { text: 'ck', hot: true },
  { text: '医用大棉签' },
  { text: 'cf活动' },
  { text: '碳仆' },
  { text: '风扇' },
  { text: '宿舍防尘罩' },
  { text: '大头棉签棒' },
  { text: '医用棉签' }
])

interface Product {
  _id: string; // 商品ID
  name: string; // 商品名称
  price: number; // 商品价格
  description: string; // 商品描述
  createdAt: Date; // 创建时间
  colorx: Array<{ context: string }>; // 商品颜色（数组，每个颜色包含 `context` 字段）
  chima: Array<{ context: string }>; // 商品尺寸（数组，每个尺寸包含 `context` 字段）
  img: string; // 商品图片（URL或路径）
  category: 'clothing' | 'shoes' | 'accessories' | 'electronics' | 'others'; // 商品分类（枚举）
}

const searchDataList = ref<Product[]>([]); // 明确指定数组元素类型
const router = useRouter()

const showSuggest = computed(() => search.value.trim() === '')

const isSearching = ref(false)

function searchData(keyword: string) {
  axios.get('http://localhost:3000/YJL/waterlist', {
    params: {
      keyword: keyword
    }
  }).then(res => {
    searchDataList.value = res.data.data
  }
  )
}

function saveHistory() {
  localStorage.setItem('searchHistory', JSON.stringify(history.value))
}

function onEnter() {
  const value = search.value.trim()
  if (!value) return
  // 如果已存在，先移除
  const existIdx = history.value.indexOf(value)
  if (existIdx !== -1) {
    history.value.splice(existIdx, 1)
  }
  // 添加到最前面
  history.value.unshift(value)
  // 限制最多6条
  if (history.value.length > 6) {
    history.value.length = 6
  }
  saveHistory()
  isSearching.value = false
  searchData(value)
}

function clickHistory(item: string) {
  search.value = item
  onEnter()
}

function clearHistory() {
  history.value = []
  saveHistory()
}

function removeItem(index: number) {
  history.value.splice(index, 1)
}

function goDetail(id: string) {
  router.push({ name: 'xiangqing', query: { id } })
}

watch(search, (val) => {
  const key = val.trim()
  if (key) {
    isSearching.value = true
    // 不立即请求，等回车
    searchDataList.value = []
  } else {
    isSearching.value = false
    searchDataList.value = []
  }
})
</script> -->
<script setup lang="ts">
import axios from 'axios'
import styles from './search.module.css'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const search = ref('')
const history = ref([
  '多功能户外重装背包',
  '硬壳冲锋衣',
  '墨镜',
  '太阳能户外防爆GPS手表'
])

const foundTags = ref([
  { text: '宿舍防尘膜' },
  { text: '鼠标' },
  { text: '防尘膜' },
  { text: 'ck', hot: true },
  { text: '医用大棉签' },
  { text: 'cf活动' },
  { text: '碳仆' },
  { text: '风扇' },
  { text: '宿舍防尘罩' },
  { text: '大头棉签棒' },
  { text: '鞋' }
])

interface Product {
  _id: string
  name: string
  price: number
  description: string
  createdAt: Date
  colorx: Array<{ context: string }>
  chima: Array<{ context: string }>
  images: string // 改为 images
  category: string // 修正为小写
}

const searchDataList = ref<Product[]>([]); // 明确指定数组元素类型
const router = useRouter()

function searchData() {
  axios.get('http://localhost:3000/YJL/waterlist', {
    params: {
      keyword: search.value
    }
  }).then(res => {
    searchDataList.value = res.data.data
  }
  )
}

function clearHistory() {
  history.value = []
}

function removeItem(index: number) {
  history.value.splice(index, 1)
}

function onEnter() {
  searchData()
  const value = search.value.trim()
  if (!value) return
  // 如果已存在，先移除
  const existIdx = history.value.indexOf(value)
  if (existIdx !== -1) {
    history.value.splice(existIdx, 1)
  }
  // 添加到最前面
  history.value.unshift(value)
  // 限制最多6条
  if (history.value.length > 6) {
    history.value.length = 6
  }
  // 清空输入框
  search.value = ''
}

function goDetail(id: string) {
  router.push({ name: 'xiangqing', query: { id } })
}

function onTagClick(val: string) {
  search.value = val
  searchData()
  // 更新历史
  const value = val.trim()
  if (!value) return
  const existIdx = history.value.indexOf(value)
  if (existIdx !== -1) {
    history.value.splice(existIdx, 1)
  }
  history.value.unshift(value)
  if (history.value.length > 6) {
    history.value.length = 6
  }
}

function goHome() {
  router.push('/home')
}
</script>

<template>
  <div :class="styles.search">
    <div :class="styles.searchBar">
      <span :class="styles.backIcon" @click="goHome">
        <svg width="22" height="22" viewBox="0 0 1024 1024" fill="gray">
          <path d="M689.6 896c-8.2 0-16.4-3.1-22.6-9.4L334.1 553.7c-12.5-12.5-12.5-32.8 0-45.3l332.9-332.9c12.5-12.5 32.8-12.5 45.3 0s12.5 32.8 0 45.3L401.3 531l311.1 311.1c12.5 12.5 12.5 32.8 0 45.3-6.2 6.3-14.4 9.6-22.6 9.6z"/>
        </svg>
      </span>
      <div style="position:relative;flex:1;">
        <input :class="styles.input" type="text" v-model="search" placeholder="搜索商品" @keydown.enter="onEnter" />
        <span :class="styles.icon" style="pointer-events:none;">
          <svg width="20" height="20" viewBox="0 0 1024 1024" fill="gray">
            <path
              d="M1002.285714 938.285714l-219.428571-219.428571q-82.285714 67.428571-188.571429 67.428571-119.428571 0-204.571429-85.142857t-85.142857-204.571429 85.142857-204.571429 204.571429-85.142857 204.571429 85.142857 85.142857 204.571429q0 106.285714-67.428571 188.571429l219.428571 219.428571q8.571429 8.571429 8.571429 20t-8.571429 20-20 8.571429-20-8.571429zM594.285714 182.857143q-92.571429 0-158.285714 65.714286t-65.714286 158.285714 65.714286 158.285714 158.285714 65.714286 158.285714-65.714286 65.714286-158.285714-65.714286-158.285714-158.285714-65.714286z">
            </path>
          </svg>
        </span>
      </div>
    </div>

    <!-- 最近搜索 -->
    <div :class="styles.historySection" v-if="history.length">
      <div :class="styles.historyHeader">
        <span>最近搜索</span>
        <span :class="styles.clearAll" @click="clearHistory">清除全部</span>
      </div>
      <ul :class="styles.tagList">
        <li v-for="item in history" :key="item" :class="styles.tagItem" @click="onTagClick(item)">
          {{ item }}
        </li>
      </ul>
    </div>
    <!-- 搜索发现 -->
    <div style="margin: 24px 16px 0 16px;">
      <div style="color:#888;font-size:15px;margin-bottom:8px;">搜索发现</div>
      <ul :class="styles.tagList">
        <li v-for="tag in foundTags" :key="tag.text" :class="styles.tagItem" @click="onTagClick(tag.text)">
          {{ tag.text }}
          <span v-if="tag.hot" :class="styles.tagHot">热</span>
        </li>
      </ul>
    </div>
    <div>
      <div v-if="searchDataList.length > 0" :class="styles.productGrid">
        <div :class="styles.productCard" v-for="item in searchDataList" :key="item._id" @click="goDetail(item._id)">
          <div :class="styles.productImgBox">
            <img :src="item.images" :alt="item.name" :class="styles.productImg" />
            <span :class="styles.productFav">♡</span>
          </div>
          <div :class="styles.productTitle">{{ item.name }}</div>
          <div :class="styles.productInfoRow">
            <span :class="styles.productStar">★ 4.6</span>
            <span :class="styles.productSold">5600人买</span>
          </div>
          <div :class="styles.productPrice">¥{{ item.price }}</div>
        </div>
      </div>
      <div v-else>
        未找到相关商品
      </div>
    </div>
  </div>
</template>
